package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.*;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyShanQian;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeShanQian;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 安心分期（出）&闪钱 全28
 * api买量 全流程
 * 链接: https://apifox.com/apidoc/shared-95cc0618-916f-4906-8b9b-70454aa5227f?pwd=GuitievI
 *
 * @author WJB
 */
@ApiPlan(productId = "323", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatShanQianPhoneMd5Convert implements ApiPlatformPhoneMd5ConvertHandler {

    private static final String KEY = "r0dx92v1oRtUJKfi";
    private static final String IV = "xwUtoo8fnivQcPO5";
    private static final String CHANNEL_CODE = "channel_6066";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        //  撞库流程
        ApiPlatDataExchangeShanQian apiPlatDataExchange = new ApiPlatDataExchangeShanQian();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiDataExchangeParameter);
        //  手机号
        apiPlatDataExchange.setMobile_md5(apiDataExchangeParameter.getPhoneMd5());
        // 城市名称
        apiPlatDataExchange.setCity(apiDataExchangeParameter.getCity());
        // 年龄
        apiPlatDataExchange.setAge(apiFieldConverter.getAgeInt());
        // 性别 0：女 1：男
        Integer sex = ChooseEq.create(apiDataExchangeParameter.getSex())
                .when("0", 1)
                .when("1", 2)
                .end(1);
        apiPlatDataExchange.setGender(sex);
        // 贷款金额
        Integer money = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanAmount(), "1", 1)
                .when(apiDataExchangeParameter.getLoanAmount(), "2", 2)
                .when(apiDataExchangeParameter.getLoanAmount(), "3", 3)
                .when(apiDataExchangeParameter.getLoanAmount(), "4", 4)
                .end(1);
        apiPlatDataExchange.setQuota(money);
        // 职业
        Integer career = ChooseEq.create(apiDataExchangeParameter.getCareer())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 4)
                .when("5", 3)
                .end(1);
        apiPlatDataExchange.setOccupation(career);
        // 房产情况
        Integer realEstateInfo = ChooseEq.create(apiDataExchangeParameter.getRealEstateInfo())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 2)
                .when("5", 2)
                .when("6", 2)
                .end(1);
        apiPlatDataExchange.setHouse(realEstateInfo);
        // 车辆情况
        Integer carInfo = ChooseEq.create(apiDataExchangeParameter.getCarInfo())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 2)
                .end(1);
        apiPlatDataExchange.setCar(carInfo);
        // 芝麻分
        Integer sesameCredit = ChooseEq.create(apiDataExchangeParameter.getSesameCredit())
                .when("1", 2)
                .when("2", 3)
                .when("3", 4)
                .when("4", 5)
                .end(2);
        apiPlatDataExchange.setZm_score(sesameCredit);
        // 社保缴纳
        Integer socialSecurity = ChooseEq.create(apiDataExchangeParameter.getSocialSecurity())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 2)
                .end(1);
        apiPlatDataExchange.setSocial_security(socialSecurity);
        // 公积金
        Integer providentFund = ChooseEq.create(apiDataExchangeParameter.getProvidentFund())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 2)
                .end(1);
        apiPlatDataExchange.setReserved_funds(providentFund);
        // 保险保单
        Integer insurancePolicy = ChooseEq.create(apiDataExchangeParameter.getInsurancePolicy())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 2)
                .end(1);
        apiPlatDataExchange.setLife_insurance(insurancePolicy);
        // 信用情况
        Integer overdue = ChooseEq.create(apiDataExchangeParameter.getOverdue())
                .when("1", 1)
                .when("2", 2)
                .when("3", 2)
                .end(1);
        apiPlatDataExchange.setOverdue(overdue);
        // 用户ip
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getIp())) {
            apiPlatDataExchange.setClient_ip(apiDataExchangeParameter.getIp());
        } else {
            apiPlatDataExchange.setClient_ip("127.0.0.1");
        }
        AES aes = AES.createCbc(KEY.getBytes(), IV.getBytes());
        Map<Object, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channel", CHANNEL_CODE);
            newMap.put("biz_data", aes.encryptToBase64Str(JsonUtils.toJson(apiPlatDataExchange)));
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        //  进件流程
        ApiPlatApplyShanQian apiPlatApply = new ApiPlatApplyShanQian();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        apiPlatApply.setName(apiApplyParameter.getUserName());
        //  手机号
        apiPlatApply.setMobile(apiApplyParameter.getPhone());
        // 城市名称
        apiPlatApply.setCity(apiApplyParameter.getCity());
        // 年龄
        apiPlatApply.setAge(apiFieldConverter.getAgeInt());
        // 性别 0：女 1：男
        Integer sex = ChooseEq.create(apiApplyParameter.getSex())
                .when("0", 1)
                .when("1", 2)
                .end(1);
        apiPlatApply.setGender(sex);
        // 贷款金额
        Integer money = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", 1)
                .when(apiApplyParameter.getLoanAmount(), "2", 2)
                .when(apiApplyParameter.getLoanAmount(), "3", 3)
                .when(apiApplyParameter.getLoanAmount(), "4", 4)
                .end(1);
        apiPlatApply.setQuota(money);
        // 职业
        Integer career = ChooseEq.create(apiApplyParameter.getCareer())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 4)
                .when("5", 3)
                .end(1);
        apiPlatApply.setOccupation(career);
        // 房产情况
        Integer realEstateInfo = ChooseEq.create(apiApplyParameter.getRealEstateInfo())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 2)
                .when("5", 2)
                .when("6", 2)
                .end(1);
        apiPlatApply.setHouse(realEstateInfo);
        // 车辆情况
        Integer carInfo = ChooseEq.create(apiApplyParameter.getCarInfo())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 2)
                .end(1);
        apiPlatApply.setCar(carInfo);
        // 芝麻分
        Integer sesameCredit = ChooseEq.create(apiApplyParameter.getSesameCredit())
                .when("1", 2)
                .when("2", 3)
                .when("3", 4)
                .when("4", 5)
                .end(2);
        apiPlatApply.setZm_score(sesameCredit);
        // 社保缴纳
        Integer socialSecurity = ChooseEq.create(apiApplyParameter.getSocialSecurity())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 2)
                .end(1);
        apiPlatApply.setSocial_security(socialSecurity);
        // 公积金
        Integer providentFund = ChooseEq.create(apiApplyParameter.getProvidentFund())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 2)
                .end(1);
        apiPlatApply.setReserved_funds(providentFund);
        // 保险保单
        Integer insurancePolicy = ChooseEq.create(apiApplyParameter.getInsurancePolicy())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 2)
                .end(1);
        apiPlatApply.setLife_insurance(insurancePolicy);

        // 用户ip
        if (ValidParam.isNotEmpty(apiApplyParameter.getIp())) {
            apiPlatApply.setClient_ip(apiApplyParameter.getIp());
        } else {
            apiPlatApply.setClient_ip("127.0.0.1");
        }
        AES aes = AES.createCbc(KEY.getBytes(), IV.getBytes());
        Map<Object, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channel", CHANNEL_CODE);
            newMap.put("biz_data", aes.encryptToBase64Str(JsonUtils.toJson(apiPlatApply)));
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) {
        //  撞库返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        JSONObject resData = jsonObject.getJSONObject("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();
        BigDecimal price = resData.getBigDecimal("price");
        String companyName = resData.getString("company_name");
        String productName = resData.getString("product_name");
        String logo = resData.getString("logo_url");

        List<ApiProtocol> protocolList = new ArrayList<>();
        //  获取协议
        JSONArray listProtocolResult = resData.getJSONArray("protocol_list");
        IteratorUtils.array(listProtocolResult, (item, index) -> {
            JSONObject protocolObject = listProtocolResult.getJSONObject(index);
            ApiProtocol protocol = new ApiProtocol();
            protocol.setProtocolName(protocolObject.getString("title"));
            protocol.setProtocolUrl(protocolObject.getString("url"));
            protocolList.add(protocol);
        });

        result.setPrice(price);
        result.setLogoPath(logo);
        result.setDisplayName(companyName);
        result.setProductName(productName);
        result.setProtocolList(protocolList);
        return result;
    }
}
